package Controllers;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import Bean.BeanClass;
import Bean.BeanStudent;
import Impl.ClassServiceImpl;
import Impl.StudentServiceImpl;
import Service.StudentService;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.fastjson.JSONArray;

import Bean.BeanBook;
import Impl.BookServiceImpl;
import cart.ShoppingCart;
import exception.BookNotFoundException;

/**
 * Servlet implementation class ShowCartController
 */
@Controller
public class ShowCartController extends HttpServlet {
	 ClassServiceImpl classService;
	 StudentServiceImpl studentService;
	    @RequestMapping("/showcart")
	    public void handleRequest(HttpServletRequest request, HttpServletResponse response)
				throws Exception {
	    	ApplicationContext applicationContext=(ApplicationContext)request.getSession().getServletContext().getAttribute("ctx");
	    	classService=(ClassServiceImpl)applicationContext.getBean("ClassServiceImpl");
	    	studentService=(StudentServiceImpl)applicationContext.getBean("StudentServiceImpl");
	        HttpSession session = request.getSession(true);
	        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");
	        if((String)session.getAttribute("userid")==null) request.getRequestDispatcher("enter").forward(request, response);
	        else {
	        String userid=(String)(session.getAttribute("userid"));
	        String aString='"'+"";

	        if (cart == null) {
	            cart = new ShoppingCart();
	            session.setAttribute("cart", cart);
	        }
	        int classId;
	        if(request.getParameter("Remove")!=null) {
	        	classId = Integer.parseInt(request.getParameter("Remove"));
	        	//cart.remove(bookId);
	        	request.getRequestDispatcher("WEB-INF/jsp/cart.jsp").forward(request, response);	
	        	return;
	        }
	        if(request.getParameter("Add")!=null) {
	        	classId = Integer.parseInt(request.getParameter("ClassId"));
	        	 try {
					 int studentid=Integer.parseInt(request.getParameter("studentid").replaceAll(aString, ""));
					 BeanStudent student=studentService.getStudent(studentid);
	                 BeanClass myclass = classService.getClassDetails(classId);
	                 cart.add(classId, myclass,student,1);
	             } catch (BookNotFoundException ex) {
	                 throw new ServletException(ex);
	             } catch (Exception e) {
					 e.printStackTrace();
				 }
				request.getRequestDispatcher("WEB-INF/jsp/cart.jsp").forward(request, response);
	        	 return;
	        }  
	        request.getRequestDispatcher("WEB-INF/jsp/cart.jsp").forward(request, response);	
	    }
	    }
}
